package com.ruoyi.web.controller.student;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;


import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException;
import com.ruoyi.common.exception.file.FileSizeLimitExceededException;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.teacher.service.IStuZxjInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.student.domain.StuZxj;
import com.ruoyi.student.service.IStuZxjService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 助学金Controller
 *
 * @author 钟彧
 * @date 2022-07-04
 */
@Api("学生奖学金接口")
@RestController
@RequestMapping("/student/zxj")
public class StuZxjController extends BaseController {
    @Autowired
    private IStuZxjService stuZxjService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IStuZxjInfoService stuZxjInfoService;

    private static final String FILE_DELIMETER = ",@\n";

    /**
     * 查询助学金列表
     */
    @ApiOperation("获取所有奖学金（通用接口）")
    @PreAuthorize("@ss.hasPermi('student:zxj:list')")
    @GetMapping("/list")
    public TableDataInfo list(StuZxj stuZxj) {
        startPage();
        //管理员查询全部，学生查询自己
        if (SecurityUtils.isAdmin(getUserId())) {
            List<StuZxj> list = stuZxjService.selectStuZxjList(stuZxj);
            return getDataTable(list);
        } else {
            try {
                if (!StringUtils.isEmpty(stuZxj.getUserId())) {
                    return new TableDataInfo(500, "非法查询", null, 0);
                } else {
                    stuZxj.setUserId(getUserId());
                    List<StuZxj> list = stuZxjService.selectStuZxjList(stuZxj);
                    return getDataTable(list);
                }
            } catch (NullPointerException e) {
                return null;
            }
        }
    }

    /**
     * 导出助学金列表
     */
    @ApiOperation("导出所有奖学金（管理员接口）")
    @PreAuthorize("@ss.hasPermi('student:zxj:export')")
    @Log(title = "助学金", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StuZxj stuZxj) {
        List<StuZxj> list = stuZxjService.selectStuZxjList(stuZxj);
        ExcelUtil<StuZxj> util = new ExcelUtil<StuZxj>(StuZxj.class);
        util.exportExcel(response, list, "助学金数据");
    }

    /**
     * 获取助学金详细信息（查看用）
     */
    @ApiOperation("id查询助学金（通用接口）")
    @PreAuthorize("@ss.hasPermi('student:zxj:query')")
    @GetMapping(value = "/{zxjId}")
    public AjaxResult getInfo(@PathVariable("zxjId") Long zxjId) {
        StuZxj stuZxj;
        AjaxResult ajaxResult = new AjaxResult();
        if (SecurityUtils.isAdmin(getUserId())) {
            stuZxj = stuZxjService.selectStuZxjByZxjId(zxjId);
        } else {
            stuZxj = stuZxjService.selectStuZxjByZxjIdAndUid(zxjId, getUserId());
        }
        //不为空时构造img数组
        if (!com.ruoyi.common.utils.StringUtils.isEmpty(stuZxj.getImageContent())) {
            ArrayList<String> srcList = new ArrayList<>();
            String[] src=stuZxj.getImageContent().split(",@\n");
            for (String src1 : src) {
                srcList.add(src1);
            }
            stuZxj.setImageContent(null);
            ajaxResult.put("srcList",srcList);
        }
        if (stuZxj.getStatus()!="0"&&stuZxj.getStatus() != null){
            ajaxResult.put("shengpi", stuZxjInfoService.getByZxjId(stuZxj.getZxjId()));
        }
        ajaxResult.put("data",stuZxj);
        return ajaxResult;
    }

    /**
     * 新增助学金
     */
    @ApiOperation("新增助学金（通用接口）")
    @PreAuthorize("@ss.hasPermi('student:zxj:add')")
    @Log(title = "助学金", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StuZxj stuZxj) {
        stuZxj.setUserId(getUserId());
        return toAjax(stuZxjService.insertStuZxj(stuZxj));
    }

    /**
     * 修改助学金
     */
    @ApiOperation("修改助学金")
    @PreAuthorize("@ss.hasPermi('student:zxj:edit')")
    @Log(title = "助学金", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StuZxj stuZxj) {
        if (SecurityUtils.isAdmin(getUserId())) {
            return error("管理员禁止修改");
        } else {
            if (stuZxj.getUserId().longValue() != getUserId().longValue()) {
                return error("非法修改：请勿修改他人表单");
            } else {
                return toAjax(stuZxjService.updateStuZxj(stuZxj));
            }
        }
    }

    /**
     * 删除助学金
     */
    @ApiOperation("通过id删除助学金")
    @PreAuthorize("@ss.hasPermi('student:zxj:remove')")
    @Log(title = "助学金", businessType = BusinessType.DELETE)
    @DeleteMapping("/{zxjIds}")
    public AjaxResult remove(@PathVariable Long[] zxjIds) {
        if (SecurityUtils.isAdmin(getUserId())) {
            return toAjax(stuZxjService.deleteStuZxjByZxjIds(zxjIds));
        } else {
            return toAjax(stuZxjService.deleteStuZxjByZxjIdsAndUid(zxjIds, getUserId()));
        }
    }

    /**
     * 新增助学金表单提交
     *
     * @param uploadFile
     * @param stuZxj
     * @return
     */
    @ApiOperation("助学金申请")
    @PostMapping("/uploads")
    @Log(title = "助学金申请", businessType = BusinessType.INSERT)
    public AjaxResult uploadFiles(List<MultipartFile> uploadFile, StuZxj stuZxj) {
        //上传执行
        try {
            AjaxResult ajax = AjaxResult.success();
            stuZxj.setUserId(getUserId());

            //判断是否有上传图片，有上传图片才执行图片提交
            if (!com.ruoyi.common.utils.StringUtils.isEmpty(uploadFile)) {
                // 上传文件路径：/upload/zxj
                String filePath = RuoYiConfig.getUploadPathZxj();
                List<String> urls = new ArrayList<String>();
                for (MultipartFile file : uploadFile) {
                    // 上传并返回新文件名称
                    file.getOriginalFilename();
                    String fileName = FileUploadUtils.upload(filePath, file, MimeTypeUtils.IMAGE_EXTENSION1);
                    String url = serverConfig.getUrl() + fileName;
                    urls.add(url);
                }
                ajax.put("urls", urls);
                //放入所有图片地址
                stuZxj.setImageContent(com.ruoyi.common.utils.StringUtils.join(urls, FILE_DELIMETER));
            }

            stuZxjService.insertStuZxj(stuZxj);
            return ajax;
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage() + "多次提交失败请联系辅导员");
        } catch (FileSizeLimitExceededException e) {
            //文件大小超出
            return AjaxResult.error(e.getMessage() + "多次提交失败请联系辅导员");
        } catch (FileNameLengthLimitExceededException e) {
            //文件名过长
            return AjaxResult.error(e.getMessage() + "多次提交失败请联系辅导员");
        } catch (InvalidExtensionException e) {
            //文件格式不正确
            return AjaxResult.error(e.getMessage() + "多次提交失败请联系辅导员");
        }
    }

    /**
     * 获取首页助学金数量信息
     *
     * @return
     */
    @GetMapping("/getIndexInfo")
    public AjaxResult getIndexInfo() {
        Long userId = getUserId();
        HashMap<String, Map> objectObjectHashMap = new HashMap<>();

        HashMap<String, Object> YTJ = new HashMap<>();
        YTJ.put("title", "已提交");
        YTJ.put("number", stuZxjService.getYTJ(userId));

        HashMap<String, Object> SHZ = new HashMap<>();
        SHZ.put("title", "审核中");
        SHZ.put("number", stuZxjService.getSHZ(userId));

        HashMap<String, Object> YTG = new HashMap<>();
        YTG.put("title", "已通过");
        YTG.put("number", stuZxjService.getYTG(userId));

        HashMap<String, Object> WTG = new HashMap<>();
        WTG.put("title", "未通过");
        WTG.put("number", stuZxjService.getWTG(userId));

        objectObjectHashMap.put("ytj", YTJ);
        objectObjectHashMap.put("shz", SHZ);
        objectObjectHashMap.put("ytg", YTG);
        objectObjectHashMap.put("wtg", WTG);
        return AjaxResult.success(objectObjectHashMap);
    }


}

